<template>
  <div class="xq-form-wrapper p24">
    <!-------------------------------------------- 搜索区域start -------------------------------------------->
    <div class="flex-center-between mb24">
      <a-space :size="24">
        <a-input-search v-if="!companyId" v-model="companyName" placeholder="用工单位名称" @change="onInputChange" />
        <a-input-search v-model="eventTitle" placeholder="服务反馈标题" @change="onInputChange" />
        <a-range-picker
          :value="dateRange"
          :placeholder="['开始月份', '结束月份']"
          :mode="['month', 'month']"
          format="YYYY-MM"
          style="width: 240px"
          @panelChange="onPanelChange"
          @change="onRangeChange"
        />
      </a-space>
      <a-space>
        <a-button v-if="companyId" type="primary" @click="goNoticeSetting"><a-icon type="bell" /> 消息提醒设置</a-button>
        <a-button type="primary" @click="showCreateModal">添加服务反馈</a-button>
      </a-space>
    </div>
    <!-------------------------------------------- 搜索区域end -------------------------------------------->
    <!-------------------------------------------- 删除添加按钮区域start -------------------------------------------->
    <div class="xq-form-main">
      <!-------------------------------------------- 删除添加按钮区域end -------------------------------------------->
      <!-------------------------------------------- 表格区域区域start -------------------------------------------->
      <a-spin :spinning="spinning" class="xq-form-content">
        <XqTable
          :scroll="{ x: columns.length * 150 }"
          :pagination="pagination"
          :customize="FormJson['config']['table']['customize']"
          :dataSource="tableData"
          :columns="columns"
          :rowSelection="
            FormJson['config']['table']['extend']['batch']
              ? {
                  selectedRowKeys: selectedRowKeys,
                  onChange: onSelectChange
                }
              : null
          "
          class="xq-form-content-table"
          @change="onTableChange"
        >
          <!--------------------------------------------主要内容，表格，自定义 header -------------------------------------------->
          <template v-for="(col, index) in columns" #[`xq_${col.dataIndex}`]>
            <span :key="index">
              {{ col.customTitle }}
            </span>
          </template>
          <!-------------------------------------------- 主要内容，表格，自定义 td -------------------------------------------->
          <template v-for="(col, index) in columns" #[col.dataIndex]="text, record">
            <!-------------------------------------------- 主操作列区域start -------------------------------------------->
            <div v-if="col.dataIndex === 'eventLabel'" :key="index">
              <template v-if="text">
                <div v-for="li in text.split(',')" :key="li" class="tag">{{ li }}</div>
              </template>
            </div>
            <div v-else-if="col.dataIndex === 'eventAnnex'" :key="index">
              <template v-if="text">
                <a v-for="li in text.split(',')" :key="li" :href="li" target="_blank" style="display: block">{{ getFileName(li, true) }}</a>
              </template>
            </div>
            <a-tooltip v-else-if="col.dataIndex === 'eventContent'" :key="index" :title="text" destroyTooltipOnHide>
              <div class="ellipsis" style="width: 140px">{{ text }}</div>
            </a-tooltip>
            <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
              <a @click="showDetailModal(record)">详情</a>
              <a-divider type="vertical" />
              <a @click="showUpdateModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm :title="`确认要删除记录吗？`" okText="确认" cancelText="取消" @confirm="deleteRecord(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <!-------------------------------------------- 主操作列区域end -------------------------------------------->
            <!-------------------------------------------- 枚举值转换start -------------------------------------------->
            <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
            <!-------------------------------------------- 枚举值转换end -------------------------------------------->
          </template>
        </XqTable>
        <!-------------------------------------------- 分页区域start -------------------------------------------->
        <div class="xq-form-content-pagination">
          <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
          <a-pagination
            v-model="currentPage"
            :pageSize="pageSize"
            :total="total"
            :showSizeChanger="true"
            :showQuickJumper="true"
            :pageSizeOptions="['20', '50', '100']"
            @change="onPageChange"
            @showSizeChange="onPageSizeChange"
          />
        </div>
        <!-------------------------------------------- 分页区域区域end -------------------------------------------->
      </a-spin>
    </div>
    <!-------------------------------------------- 表格区域end -------------------------------------------->
    <!-------------------------------------------- 添加对话框区域start -------------------------------------------->
    <a-modal
      :pagination="false"
      v-model="createModalVisible"
      :maskClosable="false"
      :destroyOnClose="true"
      title="新增服务反馈"
      :width="500"
    >
      <XqFormBuild
        ref="createForm"
        :dataSource="dsForCreate"
        :dynamicData="dynamicData"
        :formFields="FormJson['fields']"
        :formValidators="FormJson['validators']"
        :formConfig="FormJson['config']['create']"
      />
      <XqModalFooter slot="footer" @cancel="createCancel" @ok="createOk" />
    </a-modal>
    <!-------------------------------------------- 添加对话框区域end -------------------------------------------->
    <!-------------------------------------------- 编辑对话框区域start -------------------------------------------->
    <a-modal v-model="updateModalVisible" :maskClosable="false" :destroyOnClose="true" title="更新服务反馈" :width="500">
      <XqFormBuild
        ref="updateForm"
        :dataSource="tempRecord"
        :dynamicData="dynamicData"
        :formFields="FormJson['fields']"
        :formValidators="FormJson['validators']"
        :formConfig="FormJson['config']['update']"
      />
      <XqModalFooter slot="footer" @cancel="updateCancel" @ok="updateOk" />
    </a-modal>
    <a-modal
      v-model="detailModalVisible"
      :maskClosable="false"
      :destroyOnClose="true"
      title="服务反馈详情"
      :width="500"
      @cancel="detailModalVisible = false"
      class="custom-detail-modal"
    >
      <XqFormBuild
        ref="detailForm"
        :editable="false"
        :dataSource="tempRecord"
        :dynamicData="dynamicData"
        :formFields="FormJson['fields']"
        :formValidators="FormJson['validators']"
        :formConfig="FormJson['config']['detail']"
      />
      <div slot="footer"></div>
    </a-modal>
    <!-------------------------------------------- 编辑对话框区域end -------------------------------------------->
  </div>
</template>
<script>
import FormJson from "./FormJson"; // 引入FormJson数据
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import { retrieveReq, createReq, deleteReq, deleteBatchReq, updateReq } from "./api"; // 引入接口文件
import { getFileName } from "@/utils/tools";
const curdMixin = new XqCurdMixin({
  createReq,
  retrieveReq,
  updateReq,
  deleteReq,
  deleteBatchReq,
  FormJson,
  tableConfigKey: "table"
});

export default {
  name: "",
  components: {},
  mixins: [curdMixin],
  props: {
    companyId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      detailModalVisible: false,
      companyName: "",
      eventTitle: "",
      dateRange: null,
      pageSize: 20,
      companyIdList: [],
      dsForCreate: this.companyId ? { companyId: this.companyId } : {}
    };
  },
  computed: {
    retrieveParams() {
      if (this.companyId) {
        return {
          request: {
            companyId: this.companyId
          }
        };
      } else {
        return {
          request: {}
        };
      }
    },
    createParams() {
      return {};
    },
    updateParams() {
      return {};
    }
  },
  watch: {
    companyId(newVal) {
      if (newVal) {
        this.dsForCreate = {
          productTypeId: newVal
        };
      } else {
        this.dsForCreate = {};
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    showDetailModal(record) {
      this.tempRecord = record;
      this.detailModalVisible = true;
    },
    async goNoticeSetting() {
      const company = await this.$store.dispatch("hr/findCompanyItem", this.companyId);
      const comyName = company ? company.name : null;
      this.$store.dispatch("onCompanyClick", {
        id: this.companyId,
        name: comyName
      });
      this.$router.push("/message/setting?operateFromShortcut=甲方端提醒");
    },
    getFileName,
    onInputChange() {
      const params = {};
      if (this.companyName) {
        params["companyName"] = this.companyName;
      }
      if (this.eventTitle) {
        params["eventTitle"] = this.eventTitle;
      }
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      }
      this.retrieveRecord(params);
    },
    onRangeChange(value) {
      if (value && value.length === 0) {
        this.dateRange = null;
        const params = {};
        if (this.companyName) {
          params["companyName"] = this.companyName;
        }
        if (this.eventTitle) {
          params["eventTitle"] = this.eventTitle;
        }
        this.retrieveRecord(params);
      }
    },
    onPanelChange(value) {
      this.dateRange = value;
      const params = {};
      if (this.companyName) {
        params["companyName"] = this.companyName;
      }
      if (this.eventTitle) {
        params["eventTitle"] = this.eventTitle;
      }
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      }
      this.retrieveRecord(params);
    },
    async buildDynamicDataCustom(tempDynamicData) {
      this.companyIdList = await this.$request({
        url: `/hr/api/v1/companies/tileCompanyByUser`
      })
        .then((res) => {
          return res.data.map((item) => ({
            value: item.id,
            label: item.name
          }));
        })
        .catch((err) => {
          console.log(err);
          return [];
        });
      this.dynamicData = {
        ...tempDynamicData,
        companyIdList: this.companyIdList
      };
    },
    formatSearchValues(values) {
      if (values["beginTime"]) {
        values["beginTime"] = values["beginTime"].format("YYYY-MM");
      }
      if (values["endTime"]) {
        values["endTime"] = values["endTime"].format("YYYY-MM");
      }
      return values;
    },
    formatValues(values) {
      if (values["companyId"]) {
        const idx = this.companyIdList.findIndex((item) => item.value === values["companyId"]);
        if (idx > -1) {
          values["companyName"] = this.companyIdList[idx]["label"];
        }
      }
      values["eventAnnex"] = this.formatUploadValue(values["eventAnnex"]);
      values["month"] = values["month"].format("YYYY-MM");
      return values;
    },
    formatDataSource(record) {
      return record;
    }
  }
};
</script>
<style lang="scss" scoped>
.tag {
  color: #fa8c16;
  background: #fff7e6;
  border: 1px solid #ffd591;
  padding: 0 7px;
  margin-right: 8px;
  line-height: 20px;
  font-size: 12px;
  display: inline-block;
  border-radius: 4px;
}
.custom-detail-modal {
  ::v-deep .ant-modal-footer {
    display: none;
  }
  ::v-deep .ant-form-item {
    margin-bottom: 0;
  }
}
</style>
